package com.sc.core.util.DataAutoSearch;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Getter;

import java.util.List;
import java.util.Map;

@Getter
public class DataAutoSearch {
    private final SearchDTO searchDTO;
    private final QueryWrapper<?> wrapper = new QueryWrapper<>();
    public DataAutoSearch(Map<String, Object> queryMap) {
        this.searchDTO = SearchDTO.build(queryMap);
    }

    private void whereBuilder() {
        searchDTO.getSearchFields().forEach(searchField -> {
            String field = searchField.getField();
            Object value = searchField.getValue();
            switch (searchField.getType()){
                case IN -> wrapper.in(field, value);
                case LIKE -> wrapper.like(field, value);
                case EQUAL -> wrapper.eq(field, value);
                case NOT_IN -> wrapper.notIn(field, value);
                case LESS_THAN -> wrapper.lt(field, value);
                case NOT_EQUAL -> wrapper.ne(field, value);
                case GREATER_THAN -> wrapper.gt(field, value);
                case LESS_THAN_EQUAL -> wrapper.apply(field + " <= {1}", value);
                case GREATER_THAN_EQUAL -> wrapper.apply(field + " >= {1}", value);
            }
        });
    }


    private void orderBuilder() {
        searchDTO.getSearchOrders().forEach(searchOrder -> {
            wrapper.orderBy(true, searchOrder.getOrder() == SearchDTO.SearchOrder.SearchOrderType.ASC, searchOrder.getField());
        });
    }

    public String builderPage() {
        return "LIMIT " + (searchDTO.getPage() - 1) * searchDTO.getPageSize() + "," + searchDTO.getPageSize();
    }

    public QueryWrapper<?> getQueryWrapper(){
        orderBuilder();
        whereBuilder();
        return wrapper;
    }
}
